package tests;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;

import simple.http.connect.ConnectionFactory;
import simple.http.load.MapperEngine;
import simple.http.serve.Context;
import simple.http.serve.FileContext;
import trackerBT.Constants;

public class Tracker {
	public static void main(String[] args) {
		if (args.length > 0) {
			try {
				Constants.loadConfig(args[0]);
			} catch (Exception e) {
				System.err.println(
				"Configuration file not found");
				System.exit(0);
			}
		}
		else {
			System.err.println(
			"Please specify the location of the configuration file");
			System.exit(0);
		}
		new File((String) Constants.get("context")).mkdirs();
		try {
			FileWriter fw = new FileWriter((String) Constants.get("context") +
			"Mapper.xml");
			fw.write("<?xml version=\"1.0\"?>\r\n<mapper>\r\n<lookup>\r\n" +
					"<service name=\"file\" type=\"trackerBT.FileService\"/>\r\n" +
					"<service name=\"tracker\" type=\"trackerBT.TrackerService\"/>\r\n" +
					"<service name=\"upload\" type=\"trackerBT.UploadService\"/>\r\n" +
					"</lookup>\r\n<resolve>\r\n" +
					"<match path=\"/*\" name=\"file\"/>\r\n" +
					"<match path=\"/announce*\" name=\"tracker\"/>\r\n" +
					"<match path=\"/upload*\" name=\"upload\"/>\r\n" +
			"</resolve>\r\n</mapper>");
			fw.flush();
			fw.close();
		} catch (IOException ioe) {
			System.err.println("Could not create 'Mapper.xml'");
			System.exit(0);
		}
		Context context = new FileContext(new File((String) Constants.get(
		"context")));

		try {
			MapperEngine engine = new MapperEngine(context);

			ConnectionFactory.getConnection(engine).connect(new ServerSocket(
					Integer.parseInt((String)Constants.get("listeningPort"))));
			System.out.println(
					"Tracker started! Listening on port " + Constants.get("listeningPort") +
					"\r\n\r\n\t********************************************\r\n" +
					"\t*   Press enter to shut down the server    *\r\n" +
			"\t********************************************\r\n");
			// Setup the I/O buffered stream, to read user input from the command line
			InputStreamReader isr = new InputStreamReader(System.in);
			BufferedReader br = new BufferedReader(isr);
			String s = null;
			try {
				s = br.readLine();
			} catch (IOException ioe) {
			}
			System.exit(0);

		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
}
